<template>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" :size="formSize"
        status-icon>
        <el-form-item label="昵称" prop="nickname">
            <el-input v-model="ruleForm.nickname" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
            <el-upload class="avatar-uploader" action="" :http-request="uploadAvatar" :show-file-list="false"
                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="ruleForm.avatar" :src="ruleForm.avatar" class="avatar" Avatar>
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
            <el-input v-model="ruleForm.phoneNumber" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
            <el-input v-model="ruleForm.email" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="ruleForm.sex" class="ml-4">
                <el-radio label="男" size="large">男</el-radio>
                <el-radio label="女" size="large">女</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
            <el-input v-model="ruleForm.age" />
        </el-form-item>


        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                修改
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
    </el-form>
</template>
  
<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'
import { ElMessage, ElNotification } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import api from '@/api';
import store from '@/store';

interface RuleForm {
    nickname: string
    avatar: string
    phoneNumber: string
    email: string
    sex: string
    age: string

}

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<RuleForm>({
    nickname: '',
    avatar: '',
    phoneNumber: '',
    email: '',
    sex: '',
    age: ''
})

const rules = reactive<FormRules<RuleForm>>({
    phoneNumber: [
        {
            required: true,
            message: '请输入手机号',
            trigger: 'change',
        },
    ],

})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            api.user.editUser(ruleForm.value)
            .then(response => {
            // 在这里可以处理提交成功后的逻辑
            getUserById()
            ElNotification({
                title: 'Success',
                message: response.data.msg,
                type: 'success',
                duration: 1500
            });

        })
        .catch(error => {
            ElNotification({
                title: 'Error',
                message: error.data.msg,
                type: 'error',
                duration: 1500
            });
        });

        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))

const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {

    return true
}

const uploadAvatar: UploadProps['httpRequest'] = (uploadFile) => {
    const file = uploadFile.file
    // 创建FormData对象
    const formData = new FormData();
    // 将上传的文件添加到FormData中
    formData.append('file', file);

    return api.user.uploadAvatar(formData)
        .then(response => {
            // 在这里可以处理提交成功后的逻辑
            ruleForm.value.avatar = response.data.data
            ElNotification({
                title: 'Success',
                message: response.data.msg,
                type: 'success',
                duration: 1500
            });

        })
        .catch(error => {
            ElNotification({
                title: 'Error',
                message: error.data.msg,
                type: 'error',
                duration: 1500
            });
        });
}

onMounted(() => {
    getUserById()
})

function getUserById() {
    api.user.getUserById({ id: store.getters.getUserInfo.id })
        .then(response => {
            // 在这里可以处理提交成功后的逻辑
            ruleForm.value = response.data.data

        })
        .catch(error => {
            ElNotification({
                title: 'Error',
                message: error.data.msg,
                type: 'error',
                duration: 1500
            });
        });
}
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
  